//
//  LCFunction.m
//  lechuang
//
//  Created by Mr_hi on 2023/3/20.
//  Copyright © 2023 Mooyi. All rights reserved.
//

#import "LCFunction.h"
#import <CommonCrypto/CommonDigest.h>
#import <AdSupport/AdSupport.h>

@implementation LCFunction

+ (BOOL)isIphoneX {
    BOOL isIphoneX = NO;
    if (@available(iOS 11.0, *)) {
        isIphoneX = [UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom > 0.0 ? YES : NO;
    }
    return isIphoneX;
}

#pragma mark - MD5加密
+ (NSString *)ns_md5:(NSString *)string {
    const char *cStr = [string UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}


#pragma mark - 判断本地保存的数据是否为空
+ (BOOL )isWeiKong:(NSString *)str {
    BOOL isKong = NO;
    NSString *strC = [LCUserCenter objectForKey:str];
    if (strC == nil) {
        isKong = YES;
    }
    return isKong;
}

/**
 判断字典为空
 @param dic 字典
 @return YES 空 NO
 */
+ (BOOL)isBlankDictionary:(NSDictionary *)dic {
    if (!dic) {
        return YES;
    }
    if ([dic isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if (!dic.count) {
        return YES;
    }
    if (dic == nil) {
        return YES;
    }
    if (dic == NULL) {
        return YES;
    }
    if (![dic isKindOfClass:[NSDictionary class]]) {
        return YES;
    }
    return NO;
}

/** 判断字符串为空 */
+ (BOOL)isEmptyString:(id)str {
    if ((str != nil) && (![str isKindOfClass:[NSNull class]]) && ![str isEqualToString:@""]) {
        return YES;
    }
    return NO;
}

/** 字符串为空处理 */
+ (NSString *)dealEmptyString:(NSString *)string {
    if ((string != nil) && (![string isKindOfClass:[NSNull class]]) && string.length>0) {
        return string;
    }
    return @"";
}

#pragma mark - 钥匙串存数据
+ (void)KeyChainString:(NSString *)str forKey:(NSString *)key {
    [[UICKeyChainStore keyChainStore] setString:str forKey:key];
}

#pragma mark - 钥匙取出数据
+ (NSString *)KeyChainStringForKey:(NSString *)key {
    NSString *str = [[UICKeyChainStore keyChainStore] stringForKey:key];
    return str;
}

#pragma mark -  处理网页或本地Url图片
+ (NSURL *)XWX_URLImg:(NSString *)urlStr; {
    NSString *imgBan = kFORMAT(@"%@%@",XWXDomainName,urlStr);
    if ([urlStr containsString:@"https://"] || [urlStr containsString:@"Https://"] || [urlStr containsString:@"http://"] || [urlStr containsString:@"Http://"]) {
        imgBan = urlStr;
    }
    NSURL *url = [NSURL URLWithString:imgBan];
    return url;
}

#pragma mark - 处理网页或本地Str图片
+ (NSString *)XWX_URL_StrImg:(NSString *)urlStr; {
    NSString *imgBan = kFORMAT(@"%@%@",XWXDomainName,urlStr);
    NSString *imgZURL = kFORMAT(@"%@",urlStr);
    if ([imgZURL containsString:@"https://"] || [imgZURL containsString:@"Https://"] || [imgZURL containsString:@"http://"] || [imgZURL containsString:@"Http://"]) {
        imgBan = imgZURL;
    }
    return imgBan;
}

#pragma mark - 获取当前时间戳 （以毫秒为单位）
+(NSString *)getNowTimeTimestamp {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}

/**
 计算两数的值
 #param calculatetype  计算方式
 - decimalNumberByAdding：-        n1+n2
 - decimalNumberBySubtracting: -      n1-n2
 - decimalNumberByMultiplyingBy：-    n1*n2
 - decimalNumberByDividingBy：-       n1/n2
 
 #param scale    表示精确到小数点后几位,并且NSRoundingMode影响的也是scale位
 #param oneStr   第一个数值
 #param twoStr   第二个数值
 
 注意：有个不足点是当你四舍五入的后几位刚好为0时，它会默认不显示的。比如2.00保留两位数就会显示为2  2.0保留两位数也会显示为2
 
 #return 值
 */
+ (NSString *)XWXCalculateWay:(NSInteger)calculateWay WithScale:(NSInteger)scale withFirstValue:(NSString *)firstValue withSecondValue:(NSString *)secondValue {
    /***
      NSRoundBankers // 四舍五入
      NSRoundPlain   // 取整
      NSRoundDown    // 只舍不入
      NSRoundUp      // 只入不舍
     */
    NSRoundingMode mode = NSRoundBankers;
    NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler
                                       decimalNumberHandlerWithRoundingMode:mode
                                       scale:scale
                                       raiseOnExactness:NO
                                       raiseOnOverflow:NO
                                       raiseOnUnderflow:NO
                                       raiseOnDivideByZero:YES];
    
    NSDecimalNumber *subtotal = [NSDecimalNumber decimalNumberWithString:firstValue];
    NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:secondValue];
    
    NSDecimalNumber *total = [subtotal decimalNumberByAdding:discount withBehavior:roundUp];
    if (calculateWay == 1) {
        total = [subtotal decimalNumberBySubtracting:discount withBehavior:roundUp];
    } else if (calculateWay == 2) {
        total = [subtotal decimalNumberByMultiplyingBy:discount withBehavior:roundUp];
    } else if (calculateWay == 3) {
        total = [subtotal decimalNumberByDividingBy:discount withBehavior:roundUp];
    }
    
    NSString *totalStr = [total stringValue];
    if ([totalStr isEqualToString:@"NaN"]) {
        totalStr = @"0";
    }
    return totalStr;
}


// 设备信息JSon字符串
+ (NSString *)getDeviceInfo {
    NSString *udidStr = LCUserDefGet(XWX_udid);
    NSString *deviceidentifier = udidStr.length>0?udidStr:@"";  // udid
    NSString *isBreak = [LCDeviceTool isBreak]?@"1":@"0";   // 是否越狱
    NSString *isSIM = [LCDeviceTool isSIMInstalled]?@"1":@"0";  // 是否SIM卡
    NSString *isOpenGPS = @"1";  // 是否打开GPS
    NSString *isDebugMode = @"0";  // 是否调试模式
    NSString *strEdition = [LCDeviceTool deviceVersion];  // 系统版本
    NSString *strNetwork = [LCDeviceTool getYunyingshang];  // 网卡型号
    
    // 将结果返回给js
    NSDictionary *dict = @{
        @"deviceidentifier":deviceidentifier,
        @"isBreak":isBreak,
        @"isSIM":isSIM,
        @"isOpenGPS":isOpenGPS,
        @"isDebugMode":isDebugMode,
        @"strEdition":strEdition,
        @"strNetwork":strNetwork
    };
    NSLog(@"dict = %@",dict);
    
    // 将字典转化成JSON字符串
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    // 将JSON字符串转成无换行无空格字符串
    NSString *dealJsonStr = [LCFunction noWhiteSpaceString:jsonStr];
    
    return dealJsonStr;
}

// 去除掉首尾的空白字符和换行字符
+ (NSString *)noWhiteSpaceString:(NSString *)newString {
    // 去除掉首尾的空白字符和换行字符
    newString = [newString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    newString = [newString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    newString = [newString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符使用
    newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
    // 可以去掉空格，注意此时生成的strUrl是autorelease属性的，所以不必对strUrl进行release操作！
    return newString;
}

#pragma mark - 下载描述文件
+ (void)downloadConfig {
    XWX_async_get_main(^{
        // 下载.mobileconfig描述文件
        NSLog(@"downloadConfig = %@",URLConfig);
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:URLConfig]];
    });
}

/** 判断是否绑定微信 */
+ (BOOL)bangDingWeChat:(NSString *)string {
    NSString *str = [LCFunction dealEmptyString:string];
    if (str.length > 2) {
        // 有值，不为空
        NSString *stringOne = [string substringToIndex:2];
        if ([stringOne isEqualToString:@"DM"]) {
            return NO;
        }
        return YES;
    }
    return NO;
}

/// 获取字典有序value数组
/// @param dict 传入的dict
+ (NSArray *)keyVauleArrWithDictionary:(NSDictionary *)dict {
    NSMutableArray * keyValueArr = [NSMutableArray array];
    NSArray * keyArr = dict.allKeys;
    NSArray * sortedArr = [keyArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    for (NSString * key in sortedArr) {
        [keyValueArr addObject:[NSString stringWithFormat:@"%@=%@",key, dict[key]]];
    }
    return keyValueArr;
}

+ (CGSize)lc_stringSizeWithFont:(UIFont *)font str:(NSString*)str maxWidth:(CGFloat)maxWidth maxHeight:(CGFloat)maxHeight {
    NSMutableDictionary *attr = [NSMutableDictionary dictionary];
    CGSize maxSize = CGSizeMake(maxWidth, maxHeight);
    attr[NSFontAttributeName] = font;
    return [str boundingRectWithSize:maxSize options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attr context:nil].size;
}


/// 播打电话
+(void)lc_callPhoneNumber:(NSString *)phone {
    NSString *phoneNumber = [NSString stringWithFormat:@"tel:%@",phone];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber] options:@{} completionHandler:nil];
}

@end
